using UnityEngine;

namespace UFrame.Debugging
{
    public class FpsScreenBehaviour : MonoBehaviour
    {
        [SerializeField]
        public int m_targetFps = 72;
        public int m_durection = 60;
        [SerializeField]
        private float m_startWidth = 2160;
        private float m_startHeight = 1080;

        private float m_lastUpdateTime = 0f;
        private int m_frameCount = 0;

        void Start()
        {
            m_startHeight = m_startWidth * Screen.height / Screen.width;
            Screen.SetResolution((int)m_startWidth, (int)m_startHeight, true);
        }

        void Update()
        {
            m_frameCount++;
            if (Time.realtimeSinceStartup - m_lastUpdateTime >= m_durection)
            {
                var fps = m_frameCount / (Time.realtimeSinceStartup - m_lastUpdateTime);
                OnFps(fps);
                m_frameCount = 0;
                m_lastUpdateTime = Time.realtimeSinceStartup;
            }
        }

        private void OnFps(float fps)
        {
            if (Mathf.Abs(m_targetFps - fps) > 10)
            {
                var retio = fps / m_targetFps;
                var width = Mathf.FloorToInt(m_startWidth * retio);
                var height = Mathf.FloorToInt(m_startHeight * retio);
                Screen.SetResolution(width, height, true);
            }
        }
    }
}
